//
//  FileManagerUtil.m
//  ProjectTemplet
//
//  Created by HouKavin on 16/2/4.
//  Copyright © 2016年 HouKavin. All rights reserved.
//

/*
 IOS模拟器进入手机目录方法：桌面、前往、按住alt键、资源库、Application Support、IPhone Simulator、7.1、Applications、xxxxxxx(项目代号，目测是16进制代号)
 Documents 下载下来后的文件储存在这（官方解释：应用中用户数据可以放在这里，iTunes备份和恢复的时候会包括此目录）
 Library/Caches 缓存文件（官方解释：存放临时文件，iTunes不会备份和恢复此目录，此目录下文件可能会在应用退出后删除）
 tmp 下载时产生的临时文件，下载到一半放弃的“死”文件（官方解释：存放缓存文件，iTunes不会备份此目录，此目录下文件不会在应用退出删除）
 注1：iTunes在与iPhone同步时，备份所有的Documents和Library文件。
 注2：iPhone在重启时，会丢弃所有的tmp文件。
 */

#import "FileManagerUtil.h"

@implementation FileManagerUtil

+(NSString *)homePath{  //程序主目录，可见子目录(3个):Documents、Library、tmp
    return NSHomeDirectory();
}

+(NSString *)appPath{  //程序目录，不能存任何东西
    NSArray * paths = NSSearchPathForDirectoriesInDomains(NSApplicationDirectory, NSUserDomainMask, YES);
    return [paths objectAtIndex:0];
}

+(NSString *)docPath{  //文档目录，需要ITUNES同步备份的数据存这里，可存放用户数据
    NSArray * paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    return [paths objectAtIndex:0];
}

+(NSString *)libPrefPath{  //配置目录，配置文件存这里
    NSArray * paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
    return [[paths objectAtIndex:0] stringByAppendingFormat:@"/Preference"];
}

+(NSString *)libCachePath{  //缓存目录，系统永远不会删除这里的文件，ITUNES会删除
    NSArray * paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
    return [[paths objectAtIndex:0] stringByAppendingFormat:@"/Caches"];
}

+ (NSString *)tmpPath{  //临时缓存目录，APP退出后，系统可能会删除这里的内容
    return [NSHomeDirectory() stringByAppendingFormat:@"/tmp"];
}

#pragma mark - 文件存取
// 把对象归档存到沙盒里(可自定义路径)
+(void)saveObject:(id)object byFolderName:(NSString *)folderName   andFileName:(NSString*)fileName
{
    NSString *path  = [self appendFolderPath:folderName andFilePath:fileName];
    
    BOOL secc=[NSKeyedArchiver archiveRootObject:object toFile:path];
    NSLog(@"保存文件－－%@",secc==0?@"失败":@"成功");
}

// 通过文件名从沙盒中找到归档的对象(可自定义路径)
+(id)getObjectByFolderName:(NSString *)folderName  andFileName:(NSString*)fileName
{
    
    NSString *path  = [self appendFolderPath:folderName andFilePath:fileName];
    
    return [NSKeyedUnarchiver unarchiveObjectWithFile:path];
}

+(NSString *)appendFolderPath:(NSString *)folderPath  andFilePath:(NSString *)filePath {//知识库文件下载路径，这是在Documents中的一个子目录
    NSString *docPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
    NSString *downPath;
    if(folderPath.length != 0){
        downPath = [NSString stringWithFormat:@"%@/%@",docPath,folderPath];
        if (![[NSFileManager defaultManager] fileExistsAtPath:downPath]) {
            [[NSFileManager defaultManager] createDirectoryAtPath:downPath
                                      withIntermediateDirectories:YES
                                                       attributes:nil
                                                            error:NULL];
        }
    }else{
        downPath = docPath;
    }
    
    NSString *totalFile = [NSString stringWithFormat:@"%@/%@.image",downPath,filePath];
    return totalFile;
}


//清理自定义文件夹(必须在Document目录下)
+(void)cleanDocumentSonFolder:(NSString *)folderPath{
    NSString *docPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
    NSString *cleanPath;
    if (folderPath.length != 0) {
        cleanPath = [NSString stringWithFormat:@"%@/%@",docPath,folderPath];
    }else{
        cleanPath = docPath;
    }
    
    if ([[NSFileManager defaultManager] fileExistsAtPath:cleanPath]) {
        [self removeFilesAtPath:cleanPath];
        NSString *fileSize = [NSString stringWithFormat:@"文件夹内所有文件共(%.2fMB)被删除",[self folderSizeAtPath:folderPath]];
        NSLog(@"被清理的文件夹路径为 %@,%@",cleanPath,fileSize);
    }else{
        NSLog(@"要清理的文件路径'%@'不存在",cleanPath);
    }
}

//删除指定文件夹内所有内容
+(void)removeFilesAtPath:(NSString*) folderPath{
    NSFileManager* manager = [NSFileManager defaultManager];
    NSEnumerator *childFilesEnumerator = [[manager subpathsAtPath:folderPath] objectEnumerator];
    NSString* fileName;
    while ((fileName = [childFilesEnumerator nextObject]) != nil){
        NSString* fileAbsolutePath = [folderPath stringByAppendingPathComponent:fileName];
        [manager removeItemAtPath:fileAbsolutePath error:nil];
    }
}

//沙盒路径下是否存在目标文件
+(BOOL)hasLiveWithFolderPath:(NSString *)folderPath andFilePath:(NSString *)filePath{
    NSArray * paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *totalPath = [NSString stringWithFormat:@"%@/%@/%@.image",[paths objectAtIndex:0],folderPath,filePath];
    
    if ( NO == [[NSFileManager defaultManager] fileExistsAtPath:totalPath] )
    {
        return NO;
    }
    return YES;
}

#pragma mark - 遍历文件夹大小并删除
//单个文件的大小
+(long long)fileSizeAtPath:(NSString*) filePath{
    NSFileManager* manager = [NSFileManager defaultManager];
    if ([manager fileExistsAtPath:filePath]){
        return [[manager attributesOfItemAtPath:filePath error:nil] fileSize];
    }
    return 0;
}

//遍历文件夹获得文件夹大小，返回多少M
+(float)folderSizeAtPath:(NSString*) folderPath{
    NSFileManager* manager = [NSFileManager defaultManager];
    if (![manager fileExistsAtPath:folderPath]) return 0;
    NSEnumerator *childFilesEnumerator = [[manager subpathsAtPath:folderPath] objectEnumerator];
    NSString* fileName;
    long long folderSize = 0;
    while ((fileName = [childFilesEnumerator nextObject]) != nil){
        NSString* fileAbsolutePath = [folderPath stringByAppendingPathComponent:fileName];
        NSLog(@"fileAbsolutePath is %@",fileAbsolutePath);
        folderSize += [self fileSizeAtPath:fileAbsolutePath];
    }
    return folderSize/(1024.0*1024.0);
}


//清理缓存
+(void)cleanCaChe{
    NSString *fileSize = [NSString stringWithFormat:@"共清理缓存(%.2fMB)",[self folderSizeAtPath:[self libCachePath]]];
    
    //清理缓存文件夹
    [self removeFilesAtPath:[self libCachePath]];
    //提示清理了多少缓存
    NSLog(@"%@",fileSize);
}

//清理临时文件
+(void)cleanTmp{
    NSString *fileSize = [NSString stringWithFormat:@"共清理缓存(%.2fMB)",[self folderSizeAtPath:[self tmpPath]]];
    [self removeFilesAtPath:[self tmpPath]];
    //提示清理了多少缓存
    NSLog(@"%@",fileSize);
}

//清理缓存及临时文件
+(void)cleanCacheAndTmp{
    //清理缓存文件夹
    [self removeFilesAtPath:[self libCachePath]];
    //清理tmp文件夹
    [self removeFilesAtPath:[self tmpPath]];
    
    //获取清理前的缓存文件和tmp文件夹的总大小
    NSString *fileSize = [NSString stringWithFormat:@"共清理缓存(%.2fMB)",([self folderSizeAtPath:[self tmpPath]] + [self folderSizeAtPath:[self libCachePath]])];
    //提示清理了多少缓存
    NSLog(@"%@",fileSize);
}

#pragma mark - 用户设置
// 存储用户偏好设置 到 NSUserDefults
+(void)saveUserData:(id)data forKey:(NSString*)key
{
    if (data)
    {
        [[NSUserDefaults standardUserDefaults]setObject:data forKey:key];
        [[NSUserDefaults standardUserDefaults]synchronize];
    }
}
/// 读取用户偏好设置
+(id)readUserDataForKey:(NSString*)key
{
    return [[NSUserDefaults standardUserDefaults]objectForKey:key];
    
}
/// 删除用户偏好设置
+(void)removeUserDataForkey:(NSString*)key
{
    [[NSUserDefaults standardUserDefaults]removeObjectForKey:key];
}



@end
